#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "script_to_dts.h"

struct script *script;

int script_parse(const char *script_name)
{
	int	i;
	int	type;
	int	value[8];
	char	mainkey[32], subkey[32];
	struct script_section *s = NULL;

	script = script_new();
	dictionary *d = iniparser_load(script_name);
	if (d == NULL) {
		return -1;
	}
	for (i = 0; i < d->size; i++) {
		if (!d->key[i])
			continue;
		if (d->val[i]) {
			type = iniparser_get_str2int(d->val[i], value);
			if (type == -1) {
				printf("[%s][%d]script change check subkey (%s) type failed.\n",
								__func__, __LINE__, d->key[i]);
			}
			if (!(sscanf(d->key[i], "%[^:]:%[^\n]", mainkey, subkey) == 2)) {
				return -1;
			}
			switch (type) {
			case DATA_TYPE_SINGLE_WORD_HEX:
				{
				if (!script_single_hex_entry_new(s, subkey, value[0]))
					return -1;
				};
				break;
			case DATA_TYPE_SINGLE_WORD_DEC:
				{
					if (!script_single_dec_entry_new(s, subkey, value[0]))
						return -1;

				};
				break;
			case DATA_TYPE_STRING:
				{
					if (!script_string_entry_new(s, subkey, strlen(d->val[i]), (char *)(d->val[i])+1))
						return -1;
				};
				break;
			case DATA_TYPE_GPIO:
				{
					unsigned int port;
					unsigned int port_num;
					int v[4];
					port = value[0];
					port_num = value[1];
					v[0] = value[2];
					v[1] = value[3];
					v[2] = value[4];
					v[3] = value[5];
					if (!script_gpio_entry_new(s, subkey, port, port_num, v))
						return -1;
				};
				break;
			case DATA_EMPTY:
				if (!script_null_entry_new(s, subkey))
						return -1;
				break;
			default:
				printf("ERROR: Unknow section type\n");
				return -1;
			}
		} else {
			/* mainkey */
			if ((s = script_section_new(script, d->key[i])) == NULL) {
				return -1;
			}
	    }
	}
	iniparser_freedict(d);
	return 0;

}

